package cn.tedu.jdbc;

import java.sql.*;
import java.util.Scanner;

public class login {
    public static void main(String[] args) {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql:///db1?characterEncoding=utf8";
            Connection conn = DriverManager.getConnection(url, "root", "root");
            Statement st = conn.createStatement();
            String user = new Scanner(System.in).nextLine();
            String pwd = new Scanner(System.in).nextLine();
            String sql="select * from user2 where name='"+user+"'and password='"+pwd+"'";
            ResultSet rs = st.executeQuery(sql);
            if (rs.next()){
                System.out.println("登录成功");
            }else{
                System.out.println("登录失败");
            }
            st.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //解决SQL注入攻击的方案
    private static void login2() {
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql:///cgb2104?characterEncoding=utf8";
            Connection conn = DriverManager.getConnection(url, "root", "root");
//            Statement st = conn.createStatement();不行,不安全,会被SQL攻击

            String user = new Scanner(System.in).nextLine();//用户输入jack'#
            String pwd = new Scanner(System.in).nextLine();
            //?叫占位符 ,SQL的骨架
            String sql ="select * from user2 where name=? and password=?";
            //先把SQL骨架发给数据库执行
            PreparedStatement ps = conn.prepareStatement(sql);
            //给SQL里的? 设置参数
            ps.setString(1,user);//给第一个?设置值是user
            ps.setString(2,pwd);//给第二个?设置值是pwd

            ResultSet rs = ps.executeQuery();//执行拼接好的SQL,返回结果集

            if(rs.next()){
                System.out.println("登录成功~");
            }else{
                System.out.println("登录失败~");
            }
            ps.close();
            conn.close();
        }catch(Exception e){
            e.printStackTrace();//有异常,直接打印异常信息
            //System.out.println("执行失败。。。");//上线
        }
    }


}
